﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.DirectoryServices.AccountManagement;

namespace VPN
{
    public partial class UserEdit : MPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string sid = Request.QueryString["SID"];
                if (!string.IsNullOrEmpty(sid))
                {
                    System.Security.Principal.WindowsImpersonationContext wic =
                        ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
                    UserPrincipal[] user = VPN.Querier.UserHelper.GetUserInfoBySID(new string[] { sid });
                    if (user.Length == 1)
                    {
                        UserPrincipal u = user[0];
                        txtExpire.Text = u.AccountExpirationDate != null ? u.AccountExpirationDate.ToString() : string.Empty;
                        txtUsername.Text = u.Name;
                        ddlMenu.SelectedIndex = ddlMenu.Items.IndexOf(ddlMenu.Items.FindByValue(u.GetGroups().First(a => a.Name.StartsWith("Q")).Name));
                        cbEnable.Checked = u.Enabled.GetValueOrDefault(true);
                    }
                    wic.Undo();
                }
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            string sid = Request.QueryString["SID"];
            if (!string.IsNullOrEmpty(sid))
            {
                System.Security.Principal.WindowsImpersonationContext wic =
                    ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
                VPN.Querier.UserHelper.UpdateUser(sid, txtUsername.Text.Trim(), new string[] { ddlMenu.SelectedValue }, txtPassword.Text, Convert.ToDateTime(txtExpire.Text.Trim()), cbEnable.Checked);
                wic.Undo();
                Response.Redirect("UserList.aspx");
            }
        }

    }
}
